package com.chat.websocket.msg;

import com.chat.websocket.domain.MemberInfo;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author 崔超
 * 2022/2/16
 */
public class MyMessage {
    private final String senderName;
    private final String avatarUrl;
    private final String content;
    private final String time;
    private final boolean isSystem;
    private final String msgId;
    private final MessageType type;

    public static MyMessage systemTxt(String content) {
        return new MyMessage("", content, true, MessageType.TXT, "");
    }

    public static MyMessage userTxt(MemberInfo info, String content) {
        return new MyMessage(info.getNickName(), content, false, MessageType.TXT, info.getAvatarUrl());
    }

    public static MyMessage userPic(MemberInfo info, String content) {
        return new MyMessage(info.getNickName(), content, false, MessageType.PIC, info.getAvatarUrl());
    }

    public static MyMessage userFile(MemberInfo info, String fileName, int fileSize, String downloadUrl) {
        return new MyMessage(info.getNickName(), fileName + " " + fileSize + " " + downloadUrl, false, MessageType.FILE, info.getAvatarUrl());
    }

    private MyMessage(String senderName, String content, boolean isSystem, MessageType type, String avatarUrl) {
        this.senderName = senderName;
        this.content = content;
        this.isSystem = isSystem;
        this.time = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm"));
        this.msgId = UUID.randomUUID().toString().substring(0, 13);
        this.type = type;
        this.avatarUrl = avatarUrl;
    }

    public String toJson() {
        StringBuilder sb = new StringBuilder();
        sb.append("{");

        sb.append("\"msgId\":\"");
        sb.append(msgId);
        sb.append("\",");

        sb.append("\"senderName\":\"");
        sb.append(senderName);
        sb.append("\",");

        sb.append("\"isSystem\":");
        sb.append(isSystem);
        sb.append(",");

        sb.append("\"time\":\"");
        sb.append(time);
        sb.append("\",");

        sb.append("\"type\":\"");
        sb.append(type.toString());
        sb.append("\",");

        sb.append("\"avatarUrl\":\"");
        sb.append(avatarUrl);
        sb.append("\",");

        sb.append("\"content\":\"");
        sb.append(content);
        sb.append("\"");

        sb.append("}");
        return sb.toString();
    }
}
